

<template>
  <view class="">
    <view class="login-box">
      <view class="login_title"><text class="">登录</text></view>
      <view class="login_sub_title"><text class="">请登录以获得更好的云服务</text></view>
      <view class="login-form">
        <uv-form labelPosition="left" :model="form" :rules="rules" ref="uform">
          <uv-form-item label="" prop="account">
            <uv-input v-model="form.account" clearable placeholder="请输入您的账号">
            </uv-input>
          </uv-form-item>
          <uv-form-item label="" prop="password">
            <uv-input password v-model="form.password" clearable placeholder="请输入您的密码">
            </uv-input>
          </uv-form-item>
          <view>
            <view class="login_checkbox_content">
              <view class="">
                <checkbox-group @change="onRemenberMeTap"><checkbox value="true" :checked="remenberMeValue"></checkbox></checkbox-group>
              </view>
              <view class=""> 记住我 </view>
            </view>
          </view>
          <view class="login_btn" @click='onSubmit'>登录</view>

          <!-- third_account -->
<!--            
          <view class="login_third">
            <view class="login_third_title"> 第三方账号登录 </view>
            <view class="login_third_icon">
              <image class="login_third_icon_image" src="../../static/images/third_we_chat.png"></image>
            </view>
          </view> -->

        </uv-form>

        <!-- fixed_bottom_footer -->
        <view class="login_footer_ask">
          无账户？请联系您的服务商
        </view>

      </view>
    </view>

  </view>
</template>

<script setup lang="ts">
import { postLoginAPI,accountLogin, postLoginWxMinAPI, postLoginWxMinSimpleAPI } from '@/services/login'
import { useMemberStore } from '@/stores'
import type { LoginResult } from '@/types/member'
import { onLoad } from '@dcloudio/uni-app'
import { ref, reactive } from 'vue'
import { commonRegex, isWXBrowser } from '@/utils/index'
import { sendSMSVerifyCode } from '@/services/platform'
import { getWXAuthUrl } from '@/services/system'


// #ifdef MP-WEIXIN
// 获取 code 登录凭证
let code = ''
onLoad(async () => {
  const res = await wx.login()
  code = res.code
})

// 获取用户手机号码
const onGetphonenumber: UniHelper.ButtonOnGetphonenumber = async (ev) => {
  const { encryptedData, iv } = ev.detail
  const res = await postLoginWxMinAPI({ code, encryptedData, iv })
  loginSuccess(res.result)
}
// #endif


// 模拟手机号码快捷登录（开发练习）
const onGetphonenumberSimple = async () => {
  const res = await postLoginWxMinSimpleAPI('13123456789')
  loginSuccess(res.result)
}

const memberStore = useMemberStore()

const loginSuccess = (profile: LoginResult) => {
  // 保存会员信息
  memberStore.setInviter('')
  memberStore.setProfile(profile)
  // if (isInWX.value && !profile.wxmpOpenId) {
  //   // 如果在微信浏览器里面, 且没有绑定openid, 那就跳转绑定
  //   getWXAuthUrl(profile.id).then(url => {
  //     window.location.replace(url)
  //   }).catch(() => {

  //   })

  // } else {
  //   // 成功提示
  //   uni.showToast({ icon: 'success', title: '登录成功' })
  //   setTimeout(() => {
  //     // 页面跳转
  //     // uni.switchTab({ url: '/pages/my/my' })
  //     uni.navigateBack()
  //   }, 500)
  // }

  // 成功提示
  uni.showToast({ icon: 'success', title: '登录成功' })
    setTimeout(() => {
      // 页面跳转
      // uni.switchTab({ url: '/pages/my/my' })
      uni.navigateBack()
    }, 500)

}

// 传统表单登录，测试账号：13123456789 密码：123456，测试账号仅开发学习使用。
const form = ref({
  account: '',
  code: '',
  password: '',
  //inviter: memberStore.inviter
})

const loading = ref(false)

// 表单提交
const onSubmit = () => {
  uform.value.validate().then(() => {
    loading.value = true
    uni.showLoading({
      title: '登录中...',
      mask: true
    })
    accountLogin(form.value).then((data) => {
      loginSuccess(data)
    }).catch(() => { }).finally(() => {
      uni.hideLoading()
      loading.value = false
    })
  }).catch((err) => { console.log(err) })

}



const verifyCodeIns = ref()
const uform = ref()

const rules = reactive({
  account: {
    required: true,
    trigger: 'change',
    pattern: commonRegex.phone,
    message: '手机号未填写或不符合格式'
  },
  password: {
    required: true,
    trigger: 'change',
    pattern: commonRegex.password,
    message: '账号密码未填写或不符合格式'
  },
  // code: {
  //   required: true,
  //   trigger: 'blur',
  //   max: 6,
  //   min: 6,
  //   pattern: commonRegex.code,
  //   message: '验证码未填写或格式有误'
  // }
})

// #ifdef H5

const isInWX = ref(isWXBrowser())

const wxAuthUrl = ref('')
onLoad(() => {

})



const tips = ref('获取验证码')
const onCodeChange = (text) => {
  tips.value = text
}

const loginInputStyle = reactive({
  backgroundColor: '#ECF2FF',
  padding: '24rpx 18rpx',
  borderColor: 'transparent !important'
})

const canSend = ref(true)


const onCodeEnd = () => {
  canSend.value = true
}

const sendCode = () => {
  if (!verifyCodeIns.value.canGetCode) {
    uni.showToast({
      title: '暂时无法发送',
      icon: 'none'
    })
    return
  }
  uform.value.validateField('account', (err) => {
    if (err.length) {
      uni.showToast({
        title: err[0].message,
        icon: 'none'
      })
      return
    }
    uni.showLoading({
      title: '正在发送...',
      mask: true
    })
    sendSMSVerifyCode(form.value.account).then((data) => {
      uni.showToast({
        icon: 'none',
        title: `验证码已发送!${data}`
      })
      canSend.value = false
      verifyCodeIns.value.start()
    }).catch(() => { }).finally(() => { uni.hideLoading() })

  })

}

const wxMPAuth = () => {
  if (wxAuthUrl.value) {
    window.location.replace(wxAuthUrl.value)
  }
}

// #endif
const remenberMeValue = ref(false)
const onRemenberMeTap = (e) => {
  remenberMeValue.value = e.detail.value[0]
}

</script>

<style lang="scss">
.login-box {
  margin: 20px;
  .login_title{
    font-size: 32px;
    margin: 60px 0 10px 0;
  }
  .login_sub_title{
    font-size: 16px;
    color: rgba(147, 147, 147, 1);
    font-weight: 400;
  }
  .login-form {

  }
  .login_checkbox_content{
    display: flex;
    align-items: center;
    font-size: 16px;
    margin: 10px 0 10px 0;
    color: rgba(26, 102, 255, 1);
  }
  .uni-checkbox-input{
    border: 1px solid rgba(26, 102, 255, 1);
  }
  .login_btn{
    margin: 25px 0;
    border-radius: 10px;
    overflow: hidden;
    background-color: rgba(26, 102, 255, 1);
    text-align: center;
    color: white;
    padding: 10px;
  }
  .login_third{
    font-size: 14px;
    text-align: center;
    .login_third_title{
      color: rgba(51, 62, 99, 1);
      margin: 20px 0;
    }
    .login_third_icon{
      .login_third_icon_image{
        width: 48px;
        height: 48px;
      }
    }
  }

}

.login_footer_ask{
  position: fixed;
  bottom: 32px;
  font-size: 14px;
  color: gray;
  width: 100%;
  text-align: center;
}
.uv-button--info[data-v-1ac9ef43]{
  color: white;
  background-color: transparent !important;
}
</style>
